package com.ryder.book_cycle.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.book_cycle.entity.Book;
import com.ryder.book_cycle.entity.BookOrder;
import com.ryder.book_cycle.entity.BookOrderDTO;
import com.ryder.book_cycle.mapper.BookMapper;
import com.ryder.book_cycle.mapper.BookOrderMapper;
import com.ryder.book_cycle.mapper.UserAccountMapper;
import com.ryder.book_cycle.service.BookOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 描述: 订单表(BookOrder)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025-07-13 00:05:18
 */
@Service("bookOrderService")
@RequiredArgsConstructor
public class BookOrderServiceImpl extends ServiceImpl<BookOrderMapper, BookOrder> implements BookOrderService {

    private final BookMapper bookMapper;

    private final UserAccountMapper userAccountMapper;

    @Override
    @Transactional
    public boolean add(BookOrder entity) {
        // 查询是否钩库存
        Book book = bookMapper.selectById(entity.getBookId());
        Integer stock = book.getStock();
        if (stock < entity.getQuantity() || stock < 0 || entity.getQuantity() < 0) {
            return false;
        }
        boolean updated = bookMapper.updateStockById(entity.getBookId(), stock - entity.getQuantity()) > 0;
        if (!updated) {
            return false;
        }
        entity.setTotalPrice(book.getPrice() * entity.getQuantity());
        entity.setStatus(0);
        return this.save(entity);
    }

    @Override
    public Page<BookOrderDTO> selectOrderPage(Page<BookOrder> page, String bookName, String buyerName, Long merchantId) {
        return baseMapper.selectOrderPage(page, bookName, buyerName, merchantId);
    }

    @Override
    public boolean updateBookOrder(BookOrder entity, Long status) {
        // 条件更新：仅当 status=0 时才执行更新
        return update(entity,
                new LambdaUpdateWrapper<BookOrder>()
                        .eq(BookOrder::getId, entity.getId())
                        .eq(BookOrder::getStatus, status)  // 核心条件：status必须等于0
        );
    }

    @Override
    public BookOrder selectOrderDetailById(Long id) {
        return baseMapper.selectOrderDetailById(id);
    }

    @Override
    public Page<BookOrderDTO> selectUserOrderPage(Page<BookOrder> page, String bookName, Long buyerId) {
        return baseMapper.selectUserOrderPage(page, bookName, buyerId);
    }
}
